(function(document, undefined){
  
var User = window.User || {};

User.Register = (function(){

  var $u = $('#username');
  var $e = $('#email');
  
  var emailRegex = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
  var userRegex = new RegExp('^[A-Za-z][A-Za-z0-9_][A-Za-z0-9_]+$');

  
  var _initValidates = function() {
    $('#username').change(function(e) {
      var $t = $(this);
      var val = $t.val().replace(/^\s+|\s+$/, '');
      
      try {
        if (val.length == 0) {
          throw {msg: '請填寫顯示名稱'};
        }
      
        if (!userRegex.test(val)) {
          throw {msg: '顯示名稱不符合規定'};
        }
        
        $.getJSON('/rpc/user_validate', {field: 'username', value: val}, function(data){
          if (!data.ok) {
            alert('顯示名稱已有人使用!');
            $t.focus();
          }
        });
        
      } catch (e) {
        alert(e.msg);
        $t.focus();
      }
    });
    
    $('#email').change(function(e) {
      var $t = $(this);
      var val = $t.val().replace(/^\s+|\s+$/, '');
      
      try {
        if (val.length == 0) {
          throw {msg: '請填寫E-mail'};
        }
      
        if (!emailRegex.test(val)) {
          throw {msg: '不符合E-mail格式'};
        }
      } catch (e) {
        alert(e.msg);
        $t.focus();
      }
    });
    
    $('#register-form').submit(function(){
      var uval = $u.val().replace(/^\s+|\s+$/, '');
      var email = $e.val().replace(/^\s+|\s+$/, '');
      
      try {
        if (uval.length == 0) {
          throw {msg: '請填寫顯示名稱', obj: $u};
        }
      
        if (!userRegex.test(uval)) {
          throw {msg: '顯示名稱不符合規定', obj: $u};
        }
        
        if (email.length == 0) {
          throw {msg: '請填寫E-mail', obj: $e};
        }
      
        if (!emailRegex.test(email)) {
          throw {msg: '不符合E-mail格式', obj: $e};
        }
        
      } catch (e) {
        alert(e.msg);
        e.obj.focus();
        return false;
      }
    });
  };
  
  return {
    init: function() {
      _initValidates();
    }
  };
  
})();

User.Register.init();
  
})(document);